<template>
  <div class="filelist-container">
    <!-- 面包屑导航 -->
    <div class="filelist-nav">
      <div class="nav-left">
        <span v-if="curNav.length<=1">{{curNav.length==1?curNav[0].pathName:''}}</span>
        <template v-else>
          <span class="perv" @click="goBackFolder(curNav[curNav.length-2].pathId)">返回上一级</span>
          <span class="separator">|</span>
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item
              v-for="(item,index) in curNav"
              :key="index"
              :title="item.title"
              :class="item.pathId?'':'collaspe'"
              @click.native="goByNav(index,item.pathId)"
            >{{item.pathName}}</el-breadcrumb-item>
          </el-breadcrumb>
        </template>
      </div>
      <span class="nav-right">已全部加载，共{{fileList.length}}个</span>
    </div>

    <div class="filelist-wrapper">
      <!-- 文件为空时加载图片 -->
      <div class="empty-file-wrapper" v-show="fileList.length==0">
        <div
          class="empty-content"
          :style="{backgroundImage:`url(${require('../../assets/empty_imgs/empty_'+(isSearching?'2':'1')+'.png')})`}"
        >
          <p class="tips" v-if="!isSearching">
            您还没上传过文件哦，点击
            <span @click="triggerUpload">上传</span>按钮～
          </p>
          <p class="tips" v-else>
            你的网盘中，没有找到相应内容 返回
            <span @click="triggerAll">全部文件</span>
          </p>
        </div>
      </div>
      <!-- 表头 -->
      <ul class="filelist-head filelist-ul" v-show="fileList.length>0">
        <li class="li-checked" v-if="checked_items.length>0">
          <el-checkbox v-model="checkedAll" :disabled="addingFolder" @change="checkedAllFiles"></el-checkbox>
          <span class="checked-title">已选中{{checked_items.length}}个文件/文件夹</span>
        </li>
        <template v-else>
          <li class="li-filename" @click="toggleOrder('name')">
            <el-checkbox
              v-model="checkedAll"
              :disabled="addingFolder||reNaming"
              @change="checkedAllFiles"
            ></el-checkbox>
            <span class="filename">文件名</span>
            <el-icon
              class="ul-icon"
              :class="sort.attr=='name'?(sort.order==-1?'el-icon-bottom':'el-icon-top'):''"
            ></el-icon>
          </li>
          <li class="li-size text" @click="toggleOrder('size')">
            <span>大小</span>
            <el-icon
              class="ul-icon"
              :class="sort.attr=='size'?(sort.order==-1?'el-icon-bottom':'el-icon-top'):''"
            ></el-icon>
          </li>
          <li class="li-updatetime text" @click="toggleOrder('utime')">
            <span>修改日期</span>
            <el-icon
              class="ul-icon"
              :class="sort.attr=='utime'?(sort.order==-1?'el-icon-bottom':'el-icon-top'):''"
            ></el-icon>
          </li>
        </template>
      </ul>
      <!--表主体 -->
      <div class="filelist-body">
        <ul
          v-for="(item,index) in fileList"
          :key="index"
          class="documnet-list filelist-ul"
          :class="{'hover':(hover_items==index&&checked_items.length<=1)||active_hover==index||rename_index==index,
          'checked':checked_items.length>=1&&checked_items.indexOf(index)>=0
          }"
          @mouseenter="addActiveItems(index)"
          @mouseleave="delActiveItems(index)"
        >
          <li class="li-filename filename-box">
            <el-checkbox
              v-model="items_state[index]"
              :disabled="addingFolder||reNaming"
              @change="checkedItemFile(index)"
            ></el-checkbox>
            <span
              class="filetype-img"
              :style="{backgroundImage:`url(${require('../../assets/file_icons/'+item.icon+'.png')})`}"
            ></span>
            <span class="text" @click="openFile(item)">{{item.name}}</span>

            <div v-if="addingFolder&&index===0" class="new-folder-wrapper">
              <input class="new-folder-name" type="text" autofocus v-model="folderName" />
              <i class="el-icon-check folder-icon" @click="conformAddFolder"></i>
              <i class="el-icon-close folder-icon" @click="cancelAddFolder"></i>
            </div>
            <div
              v-if="reNaming&&(rename_index==index||checked_items[0]==index)"
              class="rename-wrapper"
            >
              <input class="rename-name" type="text" autofocus v-model="newFileName" />
              <i class="el-icon-check folder-icon" @click="conformNewName"></i>
              <i class="el-icon-close folder-icon" @click="cancelNewName"></i>
            </div>

            <div class="item-tool">
              <i class="el-icon-share ul-icon" title="分享" @click="shareFile(index)"></i>

              <i class="el-icon-download ul-icon" title="下载"></i>
              <!-- <el-icon class="el-icon-more ul-icon" title="更多"></el-icon> -->
              <!-- <dl class="more-wrapper">
                <dd class="command">复制到</dd>
                <dd class="command">移动到</dd>
                <dd class="command">重命名</dd>
                <dd class="command" @click="deleteFile(hover_items[0])">删除</dd>
              </dl>-->
              <el-dropdown
                placement="bottom"
                @command="handleFileCommand"
                @visible-change="visibleChange($event,index)"
              >
                <el-icon class="el-icon-more ul-icon" title="更多"></el-icon>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="0">复制到</el-dropdown-item>
                  <el-dropdown-item command="1">移动到</el-dropdown-item>
                  <el-dropdown-item command="2">重命名</el-dropdown-item>
                  <el-dropdown-item command="3">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </li>
          <li class="li-size text">{{format(item.size)}}</li>
          <li class="li-updatetime text">{{item.utime}}</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
/* import AWS from "aws-sdk"; */
//import Mock from "@/assets/mock-json.js";
import { fileAPI } from "@/utils/api.js";
import { formatSize } from "@/utils/fileList.js";
import { mapState, mapMutations } from "vuex";
import Bus from "@/upload/bus.js";
export default {
  props: {
    list: {
      type: Array,
      default: () => {
        return [];
      }
    },
    nav: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      isSearching: false,
      reNaming: false,
      checkedAll: false,
      checked_items: [],
      items_state: [],
      fileList: [],
      curNav: [],
      folderName: "新建文件夹",
      hover_items: -1,
      active_hover: -1,
      rename_index: -1,
      newFileName: ""
    };
  },
  computed: {
    ...mapState({
      addingFolder: state => state.files.adding_folder,
      sort: state => state.files.sort,
      search: state => state.files.search
      //nav: state => state.files.nav
    })
  },
  watch: {
    list: {
      deep: true,
      handler(newList) {
        this.fileList = newList;
        this.checked_items = [];
        this.items_state = new Array(newList.length).fill(false);
        this.active_hover = -1;
        this.reNaming = false;
        this.rename_index = -1;
      }
    },
    nav: {
      deep: true,
      handler(newNav) {
        this.curNav = this.showNav(newNav);
      }
    },
    checked_items: {
      deep: true,
      handler(newItems) {
        let len = newItems.length;
        //如果没有选中项，toolbar只显示只有上传和新建
        Bus.$emit("onToggleToolBar", len);
        if (len == this.fileList.length) {
          //全选
          this.checkedAll = true;
        } else {
          this.checkedAll = false;
        }
      }
    }
  },
  mounted() {
    this.items_state = new Array(this.fileList.length).fill(false);
    Bus.$on("onCreateFolder", () => {
      this.createFolder();
    });
    Bus.$on("onShareShow", () => {
      this.shareFile();
    });
    Bus.$on("onDelFile", () => {
      this.deleteFile();
    });
    Bus.$on("onReName", () => {
      this.reName();
    });
    Bus.$on("onSearch", () => {
      this.isSearching = true;
    });
    Bus.$on("onMoveShow", params => {
      this.moveType = params.type;
      this.moveFiles();
    });
    Bus.$on("onRefresh", () => {
      this.$emit("getFiles"); //重新获取当前路径文件
    });
  },
  methods: {
    ddd() {
      alert(123);
    },
    ...mapMutations(["toggleFolder", "saveNav", "saveSort"]),
    /**
     *处理导航，超过4个会省略隐藏
     */
    showNav(nav) {
      nav.forEach((el, index) => {
        nav[index].title = nav
          .slice(0, index + 1)
          .map(el => {
            return el.pathName;
          })
          .join("/");
      });
      if (nav.length > 4) {
        let newNav = nav.slice(-4);
        newNav.unshift({
          pathName: "...",
          title: newNav[0].title
        });
        return newNav;
      }
      return nav;
    },
    /**
     * 添加选择项
     */
    addActiveItems(index) {
      if (this.addingFolder || this.reNaming) return; //新建状态无法执行
      this.hover_items = index;
    },
    /**
     * 移除选择项
     */
    delActiveItems() {
      if (this.addingFolder || this.reNaming) return; //新建状态无法执行
      this.hover_items = -1;
    },
    /**
     * 新建文件夹
     */
    createFolder() {
      this.checked_items = [];
      let newFolder = {
        icon: "Folder",
        name: "-",
        utime: "-"
      };
      this.list.unshift(newFolder);
    },
    /**
     *确认新增文件夹
     */
    conformAddFolder() {
      let name = this.folderName.trim();
      if (name.length == 0) {
        this.$message.warning("文件名不能为空");
        return;
      }
      let pathId = this.nav[this.nav.length - 1].pathId;
      fileAPI.common
        .add({
          fileType: "FOLDER",
          name,
          pathId
        })
        .then(res => {
          this.$message.success("创建文件夹成功");
        })
        .catch(err => {
          console.log(err);
        })
        .finally(() => {
          this.list.shift();
          this.toggleFolder(false); //关闭新建状态
          this.$emit("getFiles"); //重新获取当前路径文件
          this.folderName = "新建文件夹";
        });
    },
    /**
     * 取消新建文件夹
     */
    cancelAddFolder() {
      this.toggleFolder(false); //关闭新建状态
      this.list.shift();
      this.folderName = "新建文件夹";
    },
    /**
     * 删除文件
     */
    deleteFile(index) {
      this.$confirm(
        "确认要把所选文件放入回收站吗？<br>删除的文件可在30天内通过回收站还原",
        "确认删除",
        {
          dangerouslyUseHTMLString: true,
          showClose: false,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        }
      )
        .then(() => {
          //确认删除
          let delList =
            index != undefined //hover的下标
              ? [this.fileList[index].id]
              : this.checked_items.map(el => {
                  //选中的下标
                  return this.fileList[el].id;
                });
          fileAPI.operate
            .delete({
              idList: delList
            })
            .then(res => {
              this.$message.success("删除文件成功");
              this.$emit("getFiles"); //重新获取当前路径文件
              Bus.$emit("onGetUserSize");
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {});
    },
    /**
     * 重命名
     */
    reName(index) {
      this.reNaming = true;
      this.rename_index =
        index != undefined && index >= 0 ? index : this.checked_items[0];
      this.newFileName = this.fileList[this.rename_index].name;
      this.checked_items = [];
      this.items_state = new Array(this.fileList.length).fill(false);
    },
    /**
     * 确认重命名
     */
    conformNewName() {
      let item = this.fileList[this.rename_index];
      let name = this.newFileName.trim();
      if (name.length == 0) {
        this.$message.warning("文件名不能为空");
        return;
      } else if (name === item.name) {
        this.$message.warning("文件名未修改");
        return;
      }
      fileAPI.operate
        .rename({
          name,
          id: item.id
        })
        .then(res => {
          this.$message.success("重命名成功");
        })
        .catch(err => {
          console.log(err);
        })
        .finally(() => {
          this.reNaming = false;
          this.$emit("getFiles"); //重新获取当前路径文件
        });
    },
    /**
     * 取消重命名
     */
    cancelNewName() {
      this.reNaming = false;
      this.rename_index = -1;
      this.newFileName = "";
    },
    shareFile(index) {
      console.log("ddd");
      let shareFileIds =
        index != undefined //hover的下标
          ? [this.fileList[index].id]
          : this.checked_items.map(el => {
              //选中的下标
              return this.fileList[el].id;
            });
      let fileName =
        index != undefined //hover的下标
          ? this.fileList[index].name
          : this.checked_items.length == 1
          ? this.fileList[this.checked_items[0]].name
          : this.fileList[this.checked_items[0]].name + "等";
      Bus.$emit("onShareFiles", {
        shareFileIds,
        fileName
      });
    },
    moveFiles(index) {
      let moveFileIds =
        index != undefined //hover的下标
          ? [this.fileList[index].id]
          : this.checked_items.map(el => {
              //选中的下标
              return this.fileList[el].id;
            });
      let parentId =
        index != undefined //父目录id
          ? this.fileList[index].parentId
          : this.fileList[this.checked_items[0]].parentId;

      Bus.$emit("onMoveFiles", {
        moveFileIds,
        parentId,
        type: this.moveType
      });
    },
    /**
     * 全选和反选
     */
    checkedAllFiles() {
      this.checked_items = [];
      let len = this.fileList.length;
      if (this.checkedAll) {
        for (let i = 0; i < len; i++) {
          this.checked_items.push(i);
        }
        this.items_state = new Array(len).fill(true);
      } else {
        this.items_state = new Array(len).fill(false);
      }
    },
    addItemFile(index) {
      //点击li选中 不能取消选中
      let i = this.checked_items.indexOf(index);
      if (i < 0) {
        //未选中 就添加
        this.checked_items.push(index);
        //this.$set(this.items_state, index, true);
        this.items_state.splice(index, 1, true);
      }
    },
    /**
     * 勾选文件
     */
    checkedItemFile(index) {
      let i = this.checked_items.indexOf(index);
      if (i < 0) {
        //未选中 就添加
        this.checked_items.push(index);
      } else {
        //选中就删除
        this.checked_items.splice(i, 1);
      }
    },
    /**
     * 下拉显示和隐藏时
     */
    visibleChange(value, index) {
      if (value) {
        this.active_hover = index;
      } else {
        this.active_hover = -1;
      }
    },
    /**
     * 列表更多操作
     */
    handleFileCommand(command) {
      switch (command) {
        case "0":
          this.moveType = "copy";
          this.moveFiles(this.active_hover);
          this.moveType = "copy";
          break;
        case "1":
          this.moveType = "move";
          this.moveFiles(this.active_hover);
          this.moveType = "move";
          break;
        case "2":
          this.reName(this.active_hover);
          break;
        case "3":
          this.deleteFile(this.active_hover);
          break;
      }
    },
    /**
     * 格式化文件大小
     */
    format(size) {
      return formatSize(size);
    },
    /**
     * 切换排序
     */
    toggleOrder(attr) {
      if (this.addingFolder || this.reNaming) return; //新建状态无法执行
      let newSort = {
        attr,
        order: this.sort.order * -1
      }; //调转顺序
      this.saveSort(newSort);
    },
    /**
     * 返回上一步
     */
    goBackFolder(id) {
      if (this.addingFolder || this.reNaming) return; //返回上一步无法执行
      this.$emit("getFiles", id);
    },
    /**
     * 点击导航跳转目录
     */
    goByNav(index, id) {
      if (this.addingFolder || this.reNaming) return; //导航跳转无法执行
      if (index != this.curNav.length - 1 && id) {
        //不是当前目录则可跳转
        this.$emit("getFiles", id);
      }
      return;
    },
    /**
     * 打开文件  目录或单文件
     */
    openFile(item) {
      if (this.addingFolder || this.reNaming) return; //打开文件无法执行
      console.log(item.type, item.id);
      if (item.type == "FOLDER") {
        //目录类型
        this.$emit("getFiles", item.id);
      } else {
        //单文件类型
        return;
      }
    },
    triggerUpload() {
      Bus.$emit("openUploader", {
        //触发上传文件
        type: "file"
      });
    },
    triggerAll() {
      this.$router.replace({ name: "all" });
    }
  },
  destroyed() {
    Bus.$off("onCreateFolder");
    Bus.$off("onShareShow");
    Bus.$off("onDelFile");
    Bus.$off("onReName");
    Bus.$off("onSearch");
    Bus.$off("onMoveShow");
    Bus.$off("onRefresh");
  }
};
</script>

<style lang="scss" scoped>
.filelist-container {
  height: calc(100% - 54px);
  overflow: hidden;
  .filelist-nav {
    padding: 0 10px;
    margin-bottom: 5px;
    font-size: 12px;
    line-height: 20px;
    height: 20px;
    .nav-left {
      float: left;
      display: flex;
      justify-content: flex-start;
      .perv {
        color: $theme-color;
      }
      .perv:hover {
        cursor: pointer;
        text-decoration: underline;
      }
      .separator {
        margin: 0 4px;
      }
    }
    .nav-right {
      float: right;
    }
  }
  .filelist-wrapper {
    height: calc(100% - 25px);
    overflow: hidden;
    position: relative;
    .empty-file-wrapper {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      .empty-content {
        width: 488px;
        padding-top: 146px;
        background-repeat: no-repeat;
        background-position: center 0;
        background-color: transparent;

        .tips {
          color: #424e67;
          text-align: center;
          span {
            color: $theme-color;
            cursor: pointer;
          }
          span:hover {
            opacity: 0.8;
          }
        }
      }
    }

    .filelist-head {
      color: #888;
      border-bottom: 1px solid #f2f6fd;
      .li-checked {
        padding-left: 10px;
      }
      .li-checked:hover {
        background-color: #fff;
        cursor: text;
      }
      .checked-title,
      .filename {
        padding-left: 12px;
      }
      .ul-icon {
        padding-left: 5px;
      }
      li {
        cursor: pointer;
      }
      li:hover {
        background-color: #f4fbff;
      }
    }
    .filelist-body {
      width: 100%;
      height: calc(100% - 36px);
      overflow-y: auto;
      overflow-x: hidden;
      .documnet-list {
        height: 44px;
        line-height: 44px;
        position: relative;
        .filename-box {
          position: relative;

          .filetype-img {
            display: block;
            height: 26px;
            width: 26px;
            position: absolute;
            left: 36px;
            top: 9px;
            background-repeat: no-repeat;
            background-position: center;
            background-image: url(../../assets/file_icons/Folder.png);
          }
          /* .folder-type {
            background: url("") 
              center;
          } */
          .text {
            display: inline-block;
            margin-left: 50px;
          }
          .item-tool {
            display: none;
            position: absolute;
            right: 25px;
            top: 0;
            height: 100%;

            .ul-icon {
              margin-right: 10px;
              font-size: 18px;
            }
            .ul-icon:hover {
              opacity: 0.8;
            }
            /* .more-wrapper {
              position: absolute;
              width: 100px;
              border: 1px solid $theme-color;
              border-radius: 3px;
              .command {
                height: 24px;
                line-height: 24px;
                color: $theme-color;
                text-align: center;
              }
            } */
          }
          .new-folder-wrapper,
          .rename-wrapper {
            position: absolute;
            right: 0;
            top: 0;
            height: 100%;
            line-height: 40px;
            width: calc(100% - 70px);
            background: transparent;
            z-index: 2;
            .new-folder-name,
            .rename-name {
              margin-left: 5px;
              border: 1px solid $theme-color;
              padding: 0 5px;
              width: 200px;
              height: 24px;
              vertical-align: middle;
              background: #fff;
              border-radius: 2px;
              color: #999666;
            }
            .new-folder-name:focus,
            .rename-name:focus {
              box-shadow: 0 0 5px 0 $theme-color;
            }
            .folder-icon {
              margin-left: 5px;
              padding: 5px;
              vertical-align: middle;
              border: 1px solid #e2e0f3;
              box-shadow: 0 0 2px 0 #e2e0f3;
              border-radius: 2px;
              background-color: #fff;
              color: $theme-color;
              font-weight: 700;
              font-size: 14px;
              cursor: pointer;
            }
          }
        }
      }
      .documnet-list:before {
        content: "";
        border-top: 1px solid #f2f6fd;
        position: absolute;
        top: -1px;
        display: block;
        width: 100%;
        z-index: 1;
      }
      .documnet-list:after {
        content: "";
        border-top: 1px solid #f2f6fd;
        position: absolute;
        bottom: 0px;
        display: block;
        width: 100%;
        z-index: 2;
      }
      .documnet-list.hover:before,
      .documnet-list.checked:before {
        border-top-color: #daebfe;
        z-index: 2;
      }
      .documnet-list.hover:after,
      .documnet-list.checked:after {
        border-top-color: #daebfe;
      }

      .documnet-list.hover,
      .documnet-list.checked {
        background: #f4fbff;
      }
      /* .documnet-list.hover.checked {
        .item-tool {
          display: none;
        }
      } */
      .documnet-list.hover {
        .li-filename {
          padding-right: 115px;
        }
        .item-tool {
          display: block;
        }
      }
    }

    .filelist-ul {
      height: 36px;
      line-height: 36px;
      font-size: 12px;
      /* overflow: hidden; */
      li {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        float: left;
      }
      .li-filename {
        padding: 0 10px;
        width: 60%;
        .text {
          cursor: pointer;
        }
        .text:hover {
          color: $theme-color;
        }
      }
      .li-size.text {
        width: 16%;

        text-indent: 10px;
      }
      .li-updatetime.text {
        width: 23%;

        text-indent: 10px;
      }
      /* .text {
        text-indent: 10px;
        cursor: pointer;
      }
      .text:hover {
        color: $theme-color;
      } */
    }
    .ul-hover {
      background: #f4fbff;
      border-color: #cbedff;
    }
    .ul-icon {
      vertical-align: text-bottom;
      font-size: 14px;
      font-weight: 700;
      color: $theme-color;
      text-indent: 0;
    }
  }
}
</style>
<style lang="scss">
.filelist-nav {
  .el-breadcrumb {
    font-size: 12px;
    line-height: 20px;
    .el-breadcrumb__item .el-breadcrumb__inner {
      color: $theme-color;
      display: inline-block;
      max-width: 100px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      vertical-align: bottom;
    }
    .el-breadcrumb__item:last-child,
    .el-breadcrumb__item.collaspe {
      .el-breadcrumb__inner {
        color: #353535;
      }
    }

    .el-breadcrumb__item:not(:last-child):hover {
      .el-breadcrumb__inner {
        cursor: pointer;
        text-decoration: underline;
      }
    }
    .el-breadcrumb__item.collaspe:hover {
      .el-breadcrumb__inner {
        cursor: text;
        text-decoration: none;
      }
    }
    .el-breadcrumb__separator {
      color: $theme-color;
    }
  }
}
.filelist-wrapper {
  .el-checkbox__input {
    .el-checkbox__inner {
      background-color: #fff !important;
      border-color: #d2d2d2 !important;
    }

    .el-checkbox__inner::after {
      border-color: $theme-color;
      border-width: 2px;
      height: 8px;
      width: 4px;
      left: 3px;
      top: 0px;
    }
  }
}
</style>